package com.example.pagingdemo.paging.githubuser;

import android.os.AsyncTask;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;
import com.example.pagingdemo.db.UserDatabase;
import com.example.pagingdemo.model.GithubUser;
import com.example.pagingdemo.paging.PageConfig;
import com.example.pagingdemo.utils.AppGlobals;

/**
 * @author: tuyrt7 on 2020/9/9.
 */
public class GithubUserViewModel extends ViewModel {

    private final LiveData<PagedList<GithubUser>> mPageData;
    private final UserDatabase mUserDatabase;

    public GithubUserViewModel() {
        mUserDatabase = UserDatabase.get(AppGlobals.getApplication());
        mPageData = new LivePagedListBuilder<>(mUserDatabase.githubUserDao().getGithubUserList(), PageConfig.INIT_SIZE)
                .setBoundaryCallback(new GithubUserBoundaryCallback(AppGlobals.getApplication()))
                .build();
    }

    public LiveData<PagedList<GithubUser>> getPageData() {
        return mPageData;
    }

    public void refresh() {
        clearData();
    }

    private void clearData() {
        AsyncTask.execute(() -> {
            mUserDatabase.githubUserDao().clear();
        });
    }
}
